'use client'
import React, { useEffect, useState } from 'react'
import Loading from '@/components/common/Loading';
import { LOCAL_USER, SESSION_INFORMATION } from '@/config/settings';
import PageTitle from '@/components/admin/common/PageTitle';
import UserInfo from '@/components/admin/Dashboard/UserInfo';
import CompanyInfo from '@/components/admin/Dashboard/CompanyInfo';
import ProductEchart from '@/components/admin/Dashboard/ProductEchart';
import PagesEchart from '@/components/admin/Dashboard/PagesEchart';
import ArticlesEchart from '@/components/admin/Dashboard/ArticlesEchart';

export default function Page() {
  const [active, setActive] = useState(false);
  const [user, setUser] = useState({});
  const [company, setCompany] = useState({});

  useEffect(() => {
    if (localStorage.getItem(LOCAL_USER)) {
      const user = JSON.parse(localStorage.getItem(LOCAL_USER));
      setUser(user);
    }
    if (sessionStorage.getItem(SESSION_INFORMATION)) {
      const company = JSON.parse(sessionStorage.getItem(SESSION_INFORMATION));
      setCompany(company);
    } else {
      fetch('/api/contact', { method: 'GET', credentials: 'include', })
        .then(response => response.json())
        .then(data => {
          setCompany(data.data);
          sessionStorage.setItem(SESSION_INFORMATION, JSON.stringify(data.data));
        })
    }
    setActive(true);
  }, [])

  const succ = (
    <div className='z-10'>
      <PageTitle title={`欢迎尊贵的：${user?.nickname}，今天是${new Date().toLocaleDateString()}，祝您工作愉快！`} />
      <div className=''>
        <div className='grid grid-cols-3 gap-2 mb-1'>
          <div className='bg-white w-full rounded-xs z-10'>
            <ProductEchart />
          </div>
          <div className='bg-white w-full rounded-xs z-10'>
            <PagesEchart />
          </div>
          <div className='bg-white w-full rounded-xs z-10'>
            <ArticlesEchart />
          </div>
        </div>
        <div className=' mx-auto grid grid-cols-3 gap-2 py-1'>
          <div className='col-span-2'><CompanyInfo companyInfo={company} userInfo={user} /></div>
          <div className='col-span-1'><UserInfo userInfo={user} /></div>
        </div>
      </div>
    </div>
  )
  return (
    <>
      {active ? succ : <Loading />}
    </>
  )
}
